package com.javaQQ;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;

public class MyFrame {
	private Socket socket = null;

	private class MyPane extends JPanel{
		private PrintWriter out = null;
		private BufferedReader in = null;
		private JTextField t;
		private JButton b;
		private DefaultListModel data = new DefaultListModel();

		public MyPane(){
			this.setLayout(new BorderLayout());

			//list
			JList l = new JList(data);
			JScrollPane sp = new JScrollPane(l);
			this.add(sp, BorderLayout.CENTER);

			JPanel p = new JPanel();
			t = new JTextField(20);
			b = new JButton("Send");
			p.add(t);
			p.add(b);
			this.add(p,BorderLayout.SOUTH);

			//stream
			try{
				out = new PrintWriter(socket.getOutputStream(),true);
				in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			}catch(Exception e){
				e.printStackTrace();
			}
			//event
			b.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent ae){
					data.addElement(t.getText());
					out.println(t.getText());
				}
			});

			new Thread(new Runnable(){
				public void run(){
					while(true){
						try{
							data.addElement(in.readLine());
						}catch(Exception e){
							return;
						}
					}
				}
			}).start();
		}
	}

	public MyFrame(String cs, Socket socket){
		this.socket = socket;

		JFrame f = new JFrame();
		f.setTitle(cs + "---" + socket.getInetAddress().getHostAddress());
		f.setLocation(200,300);
		f.setSize(320,200);
		f.getContentPane().add(new MyPane());
		f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		f.setLocationRelativeTo(null);
		f.setVisible(true);
	}
}